<?php


namespace app\common\model\divide;


use app\common\model\Setting as SettingModel;
use think\Model;

class Receive extends Model
{

    protected $name='divide_receives';


    public function user(){
        return $this->belongsTo("app\common\model\User",'user_id','user_id');
    }

    public static function getStatuslist(){
        return [0 =>'待分账', 1=> '已分账', '2' => '分账失败'];
    }
    public function wxapp(){
        return $this->belongsTo("app\common\model\Wxapp",'wxapp_id','wxapp_id');
    }

    /**
     * 从缓存中获取商城名称
     * @param $data
     * @return array
     */
    public function getStoreName($data)
    {
        $names = [];
        foreach ($data as $wxapp) {
            $names[$wxapp['wxapp_id']] = SettingModel::getItem('store', $wxapp['wxapp_id'])['name'];
        }
        return $names;
    }


    public function getList($id){
        // 获取列表数据
        return $this->with(['user','wxapp'])
            ->alias('receive')
            ->field('receive.*')
            ->join('wxapp', 'wxapp.wxapp_id = receive.wxapp_id')
            ->join('user', 'user.user_id = receive.user_id')
            ->where(['receive.receives_id' =>$id])
            ->find();
    }


    /**
     * 获取订单列表
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getReceiveList($query = [],$wxapp_id)
    {

        $where = ['receive.wxapp_id'=>$wxapp_id];
        // 设置查询条件
        !empty($query) && $this->setQueryWhere($query);

        // 获取列表数据
        return $this
            ->alias('receive')
            ->field('receive.*,user.nickName')
            ->where($where)
            ->join('wxapp', 'wxapp.wxapp_id = receive.wxapp_id')
            ->join('user', 'user.user_id = receive.user_id')
            ->order(['receive.create_time' => 'desc'])
            ->paginate(20, false, [
                'query' => request()->request()
            ]);
    }


    /**
     * 获取分红列表导出
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function bonusFinanceExport($query = [],$wxapp_id)
    {

        header("Content-type:text/html;charset=utf-8");
        $mpName = '分红记录';
        $limit = 500;//每次只从数据库取50000条以防变量缓存太大
        // buffer计数器
        $cnt = 0;
        set_time_limit(0);
        //计算总的数据
        $sqlCount = $this->getBonusFinanceExport($query,$wxapp_id,0, $limit,true);
        if($sqlCount<1){
            $this->error = '无数据导出';
            return false;
        }
        $xlsTitle = [
            '订单号', '用户昵称',  '支付金额', '是否出局', '剩余余额',
            '累计分红额',  '分红上限', '微信退款额','赏金退款额','出局转零钱','创建时间',
        ];


        $fileName = $mpName . date('Y-m-d');// 文件名称可根据自己情况设定
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

        $fileNameArr = array();
        // 逐行取出数据，不浪费内存
        for ($i = 0; $i < ceil($sqlCount / $limit); $i++) {

            $fp = fopen($fileName . '_' . $i . '.csv', 'w'); //生成临时文件
            fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
            // chmod('attack_ip_info_' . $i . '.csv',777);//修改可执行权限
            $fileNameArr[] = $fileName . '_' . $i . '.csv'; // 将数据通过fputcsv写到文件句柄
            fputcsv($fp, $xlsTitle);
            $start = $i * $limit;
            $dataArr = $this->getBonusFinanceExport($query,$wxapp_id, $start, $limit,false);

            foreach ($dataArr as $a) {
                $cnt++;
                if ($limit == $cnt) {
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                fputcsv($fp, $a);
            }
            fclose($fp);  //每生成一个文件关闭
        }

        //进行多个文件压缩
        $zip = new \ZipArchive();
        $filename = $fileName . ".zip";
        $zip->open($filename, $zip::CREATE);   //打开压缩包
        foreach ($fileNameArr as $file) {
            $zip->addFile($file, basename($file));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
        foreach ($fileNameArr as $file) {
            unlink($file); //删除csv临时文件
        }

        //输出压缩文件提供下载
        header("Cache-Control: max-age=0");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($filename)); // 文件名
        header("Content-Type: application/zip"); // zip格式的
        header("Content-Transfer-Encoding: binary"); //
        header('Content-Length: ' . filesize($filename)); //
        @readfile($filename);//输出文件;
        unlink($filename); //删除压缩包临时文件


    }



    /**
     * 获取分红列表导出
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getBonusFinanceExport($query = [],$wxapp_id,$start, $limit,$count = false)
    {

        $where = ['receive.wxapp_id'=>$wxapp_id];
        // 设置查询条件
        !empty($query) && $this->setQueryWhere($query);
         
        if($count==true){
            // 获取数据列表
            return $this->with(['user'])
                ->alias('receive')
                ->field('receive.*')
                ->where($where)
                ->join('wxapp', 'wxapp.wxapp_id = receive.wxapp_id')
                ->join('user', 'user.user_id = receive.user_id')
                ->count();
        }
        // 获取列表数据
        $list =  $this->with(['user','wxapp'])
            ->alias('receive')
            ->field('receive.*')
            ->where($where)
            ->join('wxapp', 'wxapp.wxapp_id = receive.wxapp_id')
            ->join('user', 'user.user_id = receive.user_id')
            ->limit($start,$limit)
            ->order(['receive.create_time' => 'desc'])
            ->select();

        $dataArray = [];
        foreach ($list as $order) {
            if($order['type']==0){
                $title = "未出局";
            }else{
                $title = "已出局";
            }
            $dataArray[] = [
                '订单号' => $this->filterValue($order['order_no']),
                '用户昵称' => $this->filterValue($order['user']['nickName']),
                '支付金额' => $this->filterValue($order['payment']),
                '是否出局' => $this->filterValue($title),
                '剩余余额' => $this->filterValue($order['balance']),
                '累计分红额' => $this->filterValue($order['total_abonus']),
                '分红上限' => $this->filterValue($order['top_limit']),
                '微信退款额' => $this->filterValue($order['refund_money']),
                '赏金退款额' => $this->filterValue($order['reward_money']),
                '出局转零钱' => $this->filterValue($order['small_change']),
                '创建时间' => $this->filterValue($order['create_time']),
            ];
        }

        return  $dataArray;

    }

    /**
     * 表格值过滤
     * @param $value
     * @return string
     */
    private function filterValue($value)
    {
        return "\t" . $value . "\t";
    }


    /**
     * 获取订单列表
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getAllList($query = [])
    {
        // 设置查询条件
        !empty($query) && $this->setQueryWhere($query);

        // 获取列表数据
        return $this->with(['user','wxapp'])
            ->alias('receive')
            ->field('receive.*')
            ->join('wxapp', 'wxapp.wxapp_id = receive.wxapp_id')
            ->join('user', 'user.user_id = receive.user_id')
            ->order(['receive.create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => request()->request()
            ]);
    }

    /**
     * 设置查询条件
     * @param $query
     */
    private function setQueryWhere($query)
    {
        // 设置默认的检索数据 
        $query = array_merge([
            'user_id' => 0,
            'type' => -1,
        ], $query);

        // 用户ID
      //  $params['user_id'] > 0 && $this->where('receive.user_id', '=', $params['user_id']);
        // 用户昵称/订单号

        if (isset($query['search']) && !empty($query['search'])) {
            $this->where('wxapp.wxapp_name|user.nickName|receive.transaction_id|receive.order_no', 'like', '%' . trim($query['search']) . '%');
        }

        // 支付状态
        $query['type'] > -1 && $this->where('receive.type', '=', (int)$query['type']);

        // 起始时间
        !empty($params['start_time']) && $this->where('receive.create_time', '>=', strtotime($params['start_time']));
//        // 截止时间
        !empty($params['end_time']) && $this->where('receive.create_time', '<', strtotime($params['end_time']) + 86400);
        if (isset($query['search_time']) && !empty($query['search_time'])) {
            $times=explode('至',$query['search_time']);
            $this->where('receive.create_time','between time',$times);
        }
    }

    /**
     * 设置默认的检索数据
     * @param $query
     * @param array $default
     * @return array
     */
    protected function setQueryDefaultValue(&$query, $default = [])
    {
        $data = array_merge($default, $query);
        foreach ($query as $key => $val) {
            if (empty($val) && isset($default[$key])) {
                $data[$key] = $default[$key];
            }
        }
        return $data;
    }



}